﻿using AuthCenter.API.Application.Command.Menu;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;

namespace AuthCenter.API.Application.Handler.Menu
{
    public class UpdateMenuHandler : IRequestHandler<UpdateMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public UpdateMenuHandler(IBaseRepository<MenuModel> menuRepo,
                                 IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = menuRepo.GetAll().FirstOrDefault(x => x.Id == request.Id);
            if (res == null)
            {
                result.Message = "找不到此编号";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var menu = menuRepo.GetAll().FirstOrDefault(x => x.ParentId == request.ParentId&&x.IsDel==false && x.MenuName == request.MenuName&&x.Id!=request.Id);
            if (menu != null)
            {
                result.Message = "菜单下已有此菜单名称";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map(request, res);
            model.UpdateName = request.LoginName;
            model.UpdateDate = DateTime.Now;
            int r = menuRepo.UpdateAsync(model).Result;
            if (r > 0)
            {
                result.Message = "菜单修改成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "菜单修改失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
